package vip.xiaonuo.issued.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.core.util.IpAddressUtil;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.deviceset.entity.DwDeviceSet;
import vip.xiaonuo.facedoor.modular.deviceset.service.DwDeviceSetService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.facedoor.modular.visitordevice.entity.VisitorDevice;
import vip.xiaonuo.facedoor.modular.visitordevice.service.VisitorDeviceService;
import vip.xiaonuo.facedoor.iservice.IVisitorDealWithService;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParam;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParamRet;
import vip.xiaonuo.facedoor.iservice.issulog.DeviceLogService;
import vip.xiaonuo.facedoor.remote.iservice.adapter.VisitorReqAdapter;
import vip.xiaonuo.facedoor.rule.HQRulesEngine;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.AddPersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.DeletePersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonResponse;
import vip.xiaonuo.facedoor.vo.dewo.UpdatePersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.HQAddPersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.HQDeletePersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.RequestHeader;

import java.util.Collections;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Service(value = RuleConstant.HQ+ RuleConstant.VISITOR_DEAL_WITH)
public class HQVisitorDealWithServiceImpl implements IVisitorDealWithService {

    @Autowired
    private VisitorReqAdapter visitorReqAdapter;

    @Autowired
    private VisitorDeviceService visitorDeviceService;

    @Autowired
    private DeviceLogService logService;

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private DwDeviceSetService dwDeviceSetService;




    @Override
    public PersonBaseParamRet getBaseParam(PersonBaseParam personBasePerson) {
        return new PersonBaseParamRet().setUrl("http://" + personBasePerson.getDeviceBase().getCabinetIp() + ":" + personBasePerson.getDeviceBase().getCabinetPort());
    }

    @Override
    public void deleteException(VisitorDevice visitorDevice, Visitor visitor, DeviceBase deviceBase, Exception e) {
        visitorDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
        visitorDevice.setStatus(MemberDeviceConstant.DELETE_FAIL);
        visitorDeviceService.updateById(visitorDevice);
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, UPDATE);
    }

    @Override
    public void delete(VisitorDevice visitorDevice, Visitor visitor, PersonBaseParamRet baseParam, DeviceBase deviceBase) throws Exception {
        DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
        if (deviceSet==null){
            throw new ServiceException(500,"设置尚未进行配置！");
        }
        HQDeletePersonRequest hqDeletePersonRequest = new HQDeletePersonRequest();
        HQDeletePersonRequest.InfoDTO infoDTO = new HQDeletePersonRequest.InfoDTO();
        infoDTO.setDeviceID(deviceSet.getDeviceId());
        infoDTO.setIdType(0);
        infoDTO.setTotalNum(1);
        infoDTO.setCustomizeID(Collections.singletonList(Integer.parseInt("2"+visitor.getId())));
        hqDeletePersonRequest.setInfo(infoDTO);

        DeletePersonRequest deletePersonRequest = new DeletePersonRequest();
        deletePersonRequest.setHqDeletePersonRequest(hqDeletePersonRequest);
        String uri = IFaceDoorDtoService.getBaseParam(
                deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
        String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
        RequestHeader requestHeader = new RequestHeader().setUserName("admin").setPassWord(password);
        deletePersonRequest.setRequestHeader(requestHeader);
        ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.deletePerson(uri, deletePersonRequest);
        visitorDeviceService.removeById(visitorDevice.getId());
        long count = visitorDeviceService.count(new LambdaQueryWrapper<VisitorDevice>().eq(VisitorDevice::getVisitorId, visitor.getId()));
        if (count == 0 && Objects.equals(visitor.getDelFlag(), "1")) {
            visitorService.removeById(visitorDevice.getVisitorId());
        }
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, DELETE);
    }

    @Override
    public void add(VisitorDevice visitorDevice, Visitor visitor, PersonBaseParamRet baseParam, DeviceBase deviceBase) throws Exception {
        DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
        if (deviceSet==null){
            throw new ServiceException(500,"设置尚未进行配置！");
        }
        // 获取系统配置
        Integer hqWiegandType = ConstantContextHolder.getSysConfig("HQ_WiegandType", Integer.class, true);
        Integer hq_cardMode = ConstantContextHolder.getSysConfig("HQ_CardMode", Integer.class, true);
        Integer hqRfCardMode = ConstantContextHolder.getSysConfig("HQ_RFCardMode", Integer.class, true);
        Integer hq_id_wg = ConstantContextHolder.getSysConfig("HQ_ID_WG", Integer.class, true);
        AddPersonRequest addPersonRequest = new AddPersonRequest();
        HQAddPersonRequest hqAddPersonRequest = new HQAddPersonRequest();
        HQAddPersonRequest.InfoDTO infoDTO = new HQAddPersonRequest.InfoDTO();
        infoDTO.setDeviceID(deviceSet.getDeviceId());
        infoDTO.setCustomizeID(Integer.parseInt("2"+visitor.getId()));
        // 白名单
        infoDTO.setPersonType(0);
        infoDTO.setName(visitor.getName());
        infoDTO.setGender(visitor.getSex()!=null&&visitor.getSex()==1?0:1);
        infoDTO.setNation(1);
        infoDTO.setIdCard(visitor.getIdCard());
        infoDTO.setTelnum(visitor.getTel());
        infoDTO.setTempvalid(1);
        // 韦根
        if (ObjectUtil.equal(hq_id_wg,0)){
            infoDTO.setMjCardFrom(2);
            infoDTO.setWiegandType(hqWiegandType);
            infoDTO.setWgFacilityCode(visitor.getWgFacilityCode());
            infoDTO.setMjCardNo(visitor.getIcCard());
            infoDTO.setCardMode(hq_cardMode);
            // 内置ID卡
        }else if (ObjectUtil.equal(hq_id_wg,1)){
            infoDTO.setRFCardMode(hqRfCardMode);
            infoDTO.setRFIDCard(visitor.getIcCard());
        }
        infoDTO.setValidBegin(DateUtil.format(visitor.getVisitStartDate(), "yyyy-MM-dd HH:mm:ss").replaceAll(" ","T"));
        infoDTO.setValidEnd(DateUtil.format(visitor.getVisitEndDate(), "yyyy-MM-dd HH:mm:ss").replaceAll(" ","T"));
        hqAddPersonRequest.setInfo(infoDTO);
        // 图片转换
        if (StringUtils.isNotBlank(visitor.getPhoto())){
            hqAddPersonRequest.setPicUri(IpAddressUtil.getImageAddIp(visitor.getPhoto().replace("\\","/")));

        }else {
            hqAddPersonRequest.setPicUri("");
        }
        String uri = IFaceDoorDtoService.getBaseParam(
                deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
        String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
        addPersonRequest.setHqAddPersonRequest(hqAddPersonRequest).setRequestHeader( new RequestHeader().setUserName("admin").setPassWord(password));
        ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.addPerson(uri, addPersonRequest);
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);
        visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        visitorDeviceService.updateById(visitorDevice);
    }

    @Override
    public void addException(VisitorDevice visitorDevice, Visitor visitor, DeviceBase deviceBase, Exception e) {
        visitorDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
        visitorDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
        visitorDeviceService.updateById(visitorDevice);
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, ADD);
    }

    @Override
    public void updateException(VisitorDevice visitorDevice, Visitor visitor, DeviceBase deviceBase, Exception e) {
        visitorDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
        visitorDevice.setStatus(MemberDeviceConstant.UPDATE_FAIL);
        visitorDeviceService.updateById(visitorDevice);
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, UPDATE);
    }

    @Override
    public void update(VisitorDevice visitorDevice, Visitor visitor, PersonBaseParamRet baseParam, DeviceBase deviceBase) throws Exception {
        DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
        if (deviceSet==null){
            throw new ServiceException(500,"设置尚未进行配置！");
        }
        // 获取系统配置
        Integer hqWiegandType = ConstantContextHolder.getSysConfig("HQ_WiegandType", Integer.class, true);
        Integer hq_cardMode = ConstantContextHolder.getSysConfig("HQ_CardMode", Integer.class, true);
        Integer hqRfCardMode = ConstantContextHolder.getSysConfig("HQ_RFCardMode", Integer.class, true);
        Integer hq_id_wg = ConstantContextHolder.getSysConfig("HQ_ID_WG", Integer.class, true);
        UpdatePersonRequest addPersonRequest = new UpdatePersonRequest();
        HQAddPersonRequest hqAddPersonRequest = new HQAddPersonRequest();
        HQAddPersonRequest.InfoDTO infoDTO = new HQAddPersonRequest.InfoDTO();
        infoDTO.setDeviceID(deviceSet.getDeviceId());
        infoDTO.setCustomizeID(Integer.parseInt("2"+visitor.getId()));
        infoDTO.setPersonType(0);
        infoDTO.setName(visitor.getName());
        infoDTO.setGender(visitor.getSex()!=null&&visitor.getSex()==1?0:1);
        infoDTO.setNation(1);
        infoDTO.setIdCard(visitor.getIdCard());
        infoDTO.setTelnum(visitor.getTel());
        // 韦根
        if (ObjectUtil.equal(hq_id_wg,0)){
            infoDTO.setMjCardFrom(2);
            infoDTO.setWiegandType(hqWiegandType);
            infoDTO.setWgFacilityCode(visitor.getWgFacilityCode());
            infoDTO.setMjCardNo(visitor.getIcCard());
            infoDTO.setCardMode(hq_cardMode);
            // 内置ID卡
        }else if (ObjectUtil.equal(hq_id_wg,1)){
            infoDTO.setRFCardMode(hqRfCardMode);
            infoDTO.setRFIDCard(visitor.getIcCard());
        }
        infoDTO.setTempvalid(1);
        infoDTO.setValidBegin(DateUtil.format(visitor.getVisitStartDate(), "yyyy-MM-dd HH:mm:ss").replaceAll(" ","T"));
        infoDTO.setValidEnd(DateUtil.format(visitor.getVisitEndDate(), "yyyy-MM-dd HH:mm:ss").replaceAll(" ","T"));
        hqAddPersonRequest.setInfo(infoDTO);
        // 图片转换
        if (StringUtils.isNotBlank(visitor.getPhoto())){
            hqAddPersonRequest.setPicUri(IpAddressUtil.getImageAddIp(visitor.getPhoto().replace("\\","/")));
        }else {
            hqAddPersonRequest.setPicUri("");
        }
        String uri = IFaceDoorDtoService.getBaseParam(
                deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
        String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
        addPersonRequest.setHqAddPersonRequest(hqAddPersonRequest).setRequestHeader( new RequestHeader().setUserName("admin").setPassWord(password));
        ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.updatePerson(uri, addPersonRequest);
        if (ObjectUtil.equal(returnJson.getCode(),"477")){
            throw new ServiceException(500,"请更换人员图片!");
        }
        visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        visitorDeviceService.updateById(visitorDevice);
        logService.addVisitorLog(visitor.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);

    }

}
